package com.xuhao.examai.infrastructure.persistence;

import com.xuhao.examai.domain.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserJpaRepository extends JpaRepository<User, Long> {

	Optional<User> findByUsername(String username);

	Optional<User> findByEmail(String email);

	List<User> findByRole(String role);

	boolean existsByUsername(String username);

	boolean existsByEmail(String email);

	@Query("SELECT u FROM User u WHERE u.username LIKE %:keyword% OR u.name LIKE %:keyword% OR u.email LIKE %:keyword%")
	List<User> findByKeyword(@Param("keyword") String keyword);

	@Query("SELECT u FROM User u WHERE u.role = :role AND (u.username LIKE %:keyword% OR u.name LIKE %:keyword%)")
	List<User> findByRoleAndKeyword(@Param("role") String role, @Param("keyword") String keyword);

	@Query("SELECT COUNT(u) FROM User u WHERE u.role = :role")
	Long countByRole(@Param("role") String role);

	@Query("SELECT COUNT(u) FROM User u WHERE u.isActive = true")
	Long countActiveUsers();
}